﻿using AntdUI;
using Super.Admin.Global;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Super.Admin.Utils.EventAggregator.EventType;
using Super.Admin.Utils.EventAggregator;
using Super.Admin.IServices;
using Super.Admin.Entities;
using Super.Admin.Services;
using Super.Admin.Models.User;
using Super.Admin.Mappers;
using Super.Admin.Models.Role;
using Super.Admin.Models.Department;
using System.Runtime.Intrinsics.Arm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Super.Admin.Models.Permission;
using System.Security.Policy;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Super.Admin.Views.Page
{
    public partial class RoleManagementModify : UserControl
    {
        private readonly IRoleService _roleService;
        private readonly IUserOperateLogService _userOperateLogService;
        private RoleBaseModel _roleModel;
        private List<PermissionBaseModel> _permissionModels;
        private Form _form;
        private List<int> _permissionIds;
        public RoleManagementModify(Form form, RoleBaseModel roleModel, List<PermissionBaseModel> permissionModels, IRoleService roleService, IUserOperateLogService userOperateLogService, string title)
        {
            InitializeComponent();
            _form = form;
            _roleModel = roleModel;
            _permissionModels = permissionModels;
            _roleService = roleService;
            _userOperateLogService = userOperateLogService;
            LblTitle.Text = title;
            this.Load += RoleManagementModify_Load; ;
        }

        private void RoleManagementModify_Load(object? sender, EventArgs e)
        {
            InitializeControls();
        }

        private void InitializeControls()
        {
            TreePermission.Items.Clear();
            foreach (var permission in _permissionModels)
            {
                var ti = new AntdUI.TreeItem(permission.Name) { Tag = permission.Id };
                if (permission.PermissionChildren != null && permission.PermissionChildren.Count > 0)
                {
                    SetPermissionSub(ti, permission.PermissionChildren);
                }
                TreePermission.Items.Add(ti);
            }
            TreePermission.ExpandAll();

            if (_roleModel.Id == -1)
            {
                TxtRoleName.Text = "";
                TxtRemark.Text = "";

                BtnSwitchStatus.SelectIndex = 0;
            }
            else
            {
                TxtRoleName.Text = _roleModel.Name;
                TxtRemark.Text = _roleModel.Remark;

                BtnSwitchStatus.SelectIndex = BtnSwitchStatus.Items.IndexOf(BtnSwitchStatus.Items.FirstOrDefault(i => int.Parse(i.ID) == _roleModel.IsActive));

                _permissionIds = (List<int>)_roleService.GetPermissionsByRoleId(_roleModel.Id);
                // 设置权限选中
                SetTreeChecked(TreePermission.Items);
            }
        }

        private void SetTreeChecked(TreeItemCollection list)
        {
            foreach (var tree in list)
            {
                if (_permissionIds.Contains(Convert.ToInt32(tree.Tag)))
                {
                    tree.Checked = true;
                    if (tree.Sub.Count > 0)
                    {
                        SetTreeChecked(tree.Sub);
                    }
                }
            }
        }

        private void SetPermissionSub(TreeItem ti, List<PermissionBaseModel> permissionModes)
        {
            var subList = new List<AntdUI.TreeItem>();
            foreach (var model in permissionModes)
            {
                var tis = new AntdUI.TreeItem(model.Name) { Tag = model.Id };
                if (model.PermissionChildren != null && model.PermissionChildren.Count > 0)
                {
                    SetPermissionSub(tis, model.PermissionChildren);
                }
                subList.Add(tis);
            }
            ti.Sub.AddRange(subList);
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void BtnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(TxtRoleName.Text))
                {
                    AntdUI.Message.error(_form, "请输入角色名");
                    return;
                }
                List<int> ids = new List<int>();
                foreach (TreeItem item in TreePermission.GetCheckeds())
                {
                    ids.Add(Convert.ToInt32(item.Tag));
                }
                _roleModel.Name = TxtRoleName.Text;
                _roleModel.Remark = TxtRemark.Text;
                _roleModel.IsActive = int.Parse(BtnSwitchStatus.Items[BtnSwitchStatus.SelectIndex].ID);

                if (_roleModel.Id == -1)
                {
                    _roleService.CreateRole(_roleModel.ToEntity(), ids);
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"角色管理新增：【{_roleModel.Name}】", "system:role:create");
                }
                else
                {
                    _roleService.UpdateRole(_roleModel.ToEntity(), ids);
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"角色管理修改：【{_roleModel.Name}】", "system:role:update");
                }
                AntdUI.Message.success(_form, "修改用户成功");
                this.Dispose();
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(_form, "修改用户失败：" + ex.Message);
            }
        }
    }
}